const fs=require('fs')
const path=require('path')
const _options={
  path,
  fs,
  readViews:function(url){
    const list=fs.readdirSync(path.join(this.__dirname,url));
    const views=[]
    list.forEach(function(name){
      if(/\.vue$/.test(name)){
        views.push(name.replace(/\.vue$/,''))
      }
    })
    return views
  },
  getText:function(url){
    return fs.readFileSync(path.join(this.__dirname,url)).toString()
  },
  getSuiMap(url,hasText){
    const dir=path.join(this.__dirname,url);
    let name='';
    url.replace(/\w+$/,function (m){
      name=m
    })
    const flist=fs.readdirSync(dir);
    const suiMap={
      name:name,
      list:[],
    }
    if(hasText){
      suiMap.textList=[]
    }
    flist.forEach(function(filepath){
      if(/\.vue$/.test(filepath)){
        const name =filepath.replace('.vue', '')
        const text = fs.readFileSync(path.join(dir,filepath)).toString()
        suiMap.list.push(name)
        if(hasText){
          suiMap.textList.push(text)
        }
      }
    })
    return suiMap;
  },
}
//让前端的js可以执行nodejs
module.exports = function (content, map, meta) {
  if(/NodeJs\.(\w+\([\d\D]+?\))/.test(content)){
    var options = Object.assign({
      __dirname:this.context
    },_options);
    content=content.replace(/NodeJs\.(\w+\([\d\D]+?\))/g,function (m,p1) {
      const func=new Function('obj','with(obj){return '+p1+'}')
      const data=func(options)
      if(typeof data==='string'){
        return data;
      }
      return JSON.stringify(data)
    })
  }
  return content;
}
